<template >
	<!-- eslint-disable vue/no-mutating-props  -->
	<el-form :model="source" :size="size" v-bind="formOption" ref="formFef">
		<slot
			:name="field_name"
			v-for="(propertie, field_name) in schema.properties"
			:key="field_name"
			v-bind:data="{ propertie, source }"
		>
			<el-form-item
				:label="formItemlabel(propertie.label)"
				:key="field_name"
				:prop="field_name"
				:rules="propertie.rules"
			>
				<component
					:is="componentName(propertie.type)"
					v-model="source[field_name]"
					v-bind="handleProp(propertie.type, propertie.props, propertie)"
				>
				</component>
			</el-form-item>
		</slot>
		<slot name="submitFormItem">
			<el-form-item class="submit-form-item">
				<el-button class="submit" type="primary" size="small" @click="submit">提交</el-button>
			</el-form-item>
		</slot>
	</el-form>
</template>
<script>
import AutoFormSelect from '@/common/components/AutoForm/select'
export default {
	name: 'AutoForm',
	components: { AutoFormSelect },
	props: {
		schema: { type: Object },
		source: { type: Object },
		size: {
			default: 'small',
			type: String,
		},
		formOption: {
			type: Object,
			default: () => {
				return {
					'label-width': '90px',
				}
			},
		},
		formItemWidth: {
			type: String,
			default: '240px',
		},
		submit: {
			type: Function,
			null: true,
		},
	},
	data() {
		return {}
	},
	methods: {
		validate(func) {
			this.$refs['formFef'].validate(func)
		},
		formItemlabel(label) {
			return label + ':'
		},
		componentName(key) {
			switch (key) {
				case 'string':
					return 'el-input'
				case 'text':
					return 'el-input'
				case 'number':
					return 'el-input-number'
				case 'boolean':
					return 'el-switch'
				case 'select':
					return 'AutoFormSelect'
				case 'datetime':
					return 'el-date-picker'
				case 'time':
					return 'el-time-picker'
				case 'date':
					return 'el-date-picker'
				default:
					return 'el-input'
			}
		},
		handleProp(type, props, propertie) {
			var _props = {}
			// _props.size = 'small'
			_props.style = { width: this.formItemWidth }
			_props.placeholder = '请输入' + propertie.label
			if (type === 'select') _props.placeholder = '请选择' + propertie.label
			switch (type) {
				case 'text':
					_props.type = 'textarea'
					break
				case 'datetime':
					_props.type = 'datetime'
					break
				case 'date':
					_props.type = 'date'
					break
				// case 'number':
				// 	_props.style = { width: '100%' }
				// 	break
			}
			Object.assign(_props, props)
			return _props
		},
	},
}
</script>
<style lang='scss' scoped>
.submit-form-item {
	.submit {
		width: 200px;
	}
}
</style>